import {Commit, createStore} from 'vuex'
import {TodoItem} from "@/TodoPage/DataTypes";

interface IState {
    toDoList: TodoItem[]
}

interface ICxt {
    commit: Commit,
    state: IState
}

export const ADD_TODO = "ADD_TODO";
export const UPDATE_STATUS = "UPDATE_STATUS";
export const DELETE_STATUS = "DELETE_STATUS";


export default createStore({
    // 根级别全局数据
    state: {
        toDoList: [],
    },
    // 改变state中数据的方法 ；
    mutations: {
        [ADD_TODO](state: IState, toDoItem: TodoItem) {
            state.toDoList.unshift(toDoItem)
        },
        [UPDATE_STATUS](state: IState, toDoItem: TodoItem) {
            const index = state.toDoList.findIndex(it => it.id === toDoItem.id)
            if (index > 0) {
                state.toDoList[index].status = toDoItem.status;
            }
        },
        [DELETE_STATUS](state: IState, id: number) {
            const index = state.toDoList.findIndex(it => it.id === id)
            if (index >= 0) {
                state.toDoList.splice(index, 1)
            }

        },
    },
    // 调用 mutations中的方法。或者一些异步的方法；
    actions: {
        [ADD_TODO]({commit}: ICxt, toDoItem: TodoItem): void {
            commit(ADD_TODO, toDoItem)
        },
        [UPDATE_STATUS]({commit}: ICxt, toDoItem: TodoItem): void {
            commit(UPDATE_STATUS, toDoItem)
        },
        [DELETE_STATUS]({commit}: ICxt, id: number): void {
            commit(DELETE_STATUS, id)
        },
    },
    // 不同 的命名空间
    modules: {}
})
